import React, { useEffect, useMemo, useState } from "react";
import { Button, Input, message, Modal, Tree, Typography } from "antd";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import debounce from "lodash/debounce";

import request from "@/utils/request";
// import AddModal from './AddModal'
import { useAppSelector } from "@/utils/hooks";
import { getAllParentIds, plainTree, transformTreeData } from "@/utils/util";

import { RecordDetail } from "../type";
import AddModal from "@/views/AuthManage/RoleManage/RoleSide/AddModal";

interface Props {
	editDetail?: RecordDetail;
	onSelect: (keys: React.Key[]) => void;
}

const getFirstRole = (roleList: Role[]): Role => {
	const walk = (roleList: Role[]): Role | undefined => {
		for (let i = 0; i < roleList.length; i++) {
			const item = roleList[i]
			if (item.parentId) {
				return item
			} else if (item.children) {
				return walk(item.children)
			}
		}
	}
	return walk(roleList) as Role
}

const RoleSide: React.FC<Props> = ({ onSelect, editDetail }) => {
	const [app] = useAppSelector(state => [state.app])

	const [addOpen, setAddOpen] = useState(false)
	const [treeList, setTreeList] = useState<Role[]>([])
	const [searchVal, setSearchVal] = useState('')
	const [selectedKeys, setSelectedKeys] = useState<React.Key[]>()
	const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([])
	const [autoExpandParent, setAutoExpandParent] = useState(true)

	useEffect(() => {
		queryRoleList()
	}, [editDetail,app.currentEntity])

	const queryRoleList = () => {
		const data = { tenantId: app.currentEntity.entityId }
		request('roleManageRoleList', { data }).then(res => {
			if (res.code === 0 && res.data) {
				const transedTreeList = res.data;
				setTreeList(transedTreeList)
				if (editDetail?.roleId) {
					handleSelect([editDetail.roleId])
				} else {
					const firstRole = getFirstRole(transedTreeList) || {}
					console.log(firstRole,expandedKeys)
					setExpandedKeys([...expandedKeys, firstRole?.key as React.Key])
					handleSelect([firstRole.key!])
				}
			}
		})
	}

	const handleAddClick = () => {
		setAddOpen(true)
	}

	const plainedList = useMemo(() => {
		return plainTree(treeList)
	}, [treeList])

	const handleInputChange = debounce((e: React.ChangeEvent<HTMLInputElement>) => {
		const value = e.target.value
		const nodeKeys = plainedList
			.map(item => {
				if ((item.title as string).indexOf(value) > -1) {
					return item.key
				}
				return null
			})
			.filter((item, i, self) => item && self.indexOf(item) === i)

		const newExpandedKeys = getAllParentIds(treeList, nodeKeys as React.Key[])
		setExpandedKeys(newExpandedKeys as React.Key[])
		setSearchVal(value)
		setAutoExpandParent(true)
	}, 300)

	const treeData = useMemo(() => {
		const loop = (data: Role[]): Role[] =>
			data.map(item => {
				const strTitle = item.title as string
				const index = strTitle.indexOf(searchVal)
				const beforeStr = strTitle.substring(0, index)
				const afterStr = strTitle.slice(index + searchVal.length)
				const title: any =
					index > -1 ? (
						<span>
              {beforeStr}
							<span className="site-tree-search-value">{searchVal}</span>
							{afterStr}
            </span>
					) : (
						<span>{strTitle}</span>
					)
				if (item.children) {
					return { ...item, title, key: item.key, children: loop(item.children) }
				}
				return {
					...item,
					title,
					key: item.key,
				}
			})
		return loop(treeList)
	}, [searchVal, treeList])

	const remove = (nodeData: Role) => {
		Modal.confirm({
			title: '提示',
			content: `是否将${nodeData.roleName}角色删除？`,
			onOk() {
				return request('roleManageDeleteRole', { data: { roleId: nodeData.value } }).then(res => {
					if (res.code === 0) {
						message.success('删除成功')
						queryRoleList()
					}
				})
			},
		})
	}

	const renderTitle = (nodeData: Role) => {
		return (
			<div className="betweenCenter">
				<span>{nodeData.title}</span>
				{nodeData.parentId && (
					<span className="ml20" onClick={() => remove(nodeData)}>
            <DeleteOutlined></DeleteOutlined>
          </span>
				)}
			</div>
		)
	}

	const handleSelect = (selectedKeys: React.Key[], info?: { node: Role }) => {
		if (info?.node && !info?.node.parentId) {
			// 选择父节点的情况
			return
		}
		setSelectedKeys(selectedKeys)
		onSelect(selectedKeys)
	}

	const handleExpand = (newExpandedKeys: React.Key[]) => {
		setExpandedKeys(newExpandedKeys)
		setAutoExpandParent(false)
	}

	return (
		<div className="role-manage-sider">
			<div className="betweenCenter mb20">
				<Typography.Title level={5} style={{ margin: 0 }}>
					角色列表
				</Typography.Title>
				<Button icon={<PlusOutlined />} onClick={handleAddClick}>
					添加角色
				</Button>
			</div>
			<Input.Search
				allowClear
				style={{ marginBottom: 8 }}
				placeholder="请输入角色名称"
				onChange={handleInputChange}
			/>
			{!!treeData.length && (
				<Tree
					blockNode
					// defaultExpandAll
					className="role-manage-sider-tree mt5 breakWord"
					autoExpandParent={autoExpandParent}
					expandedKeys={expandedKeys}
					onExpand={handleExpand}
					selectedKeys={selectedKeys}
					onSelect={handleSelect}
					titleRender={renderTitle}
					treeData={treeData}
				/>
			)}

			<AddModal
				open={addOpen}
				onCancel={() => setAddOpen(false)}
				onSearch={queryRoleList}
			></AddModal>
		</div>
	)
}

export default RoleSide
